package com.nulldev.util.web.nTube.pages.invidious_compat;

import com.nulldev.util.JVM.JVM;
import com.nulldev.util.languages.json.uniapi.UniJsonValue;
import com.nulldev.util.web.HttpServer3.Response;
import com.nulldev.util.web.HttpServer3.pages.v3.HttpPage3;
import com.nulldev.util.web.YouTubeExtractor.comments.YTComment;
import com.nulldev.util.web.YouTubeExtractor.comments.YTComments;
import com.nulldev.util.web.YouTubeExtractor.comments.YTComments.YTCommentInitData;
import com.nulldev.util.web.YouTubeExtractor.comments.YTComments.YouTubeCommentResult;

public class APIComments extends HttpPage3 {

	public APIComments() {
		super("/api/v1/comments/");
		this.setCachingMethod(CachingMethod.NO_CACHE);
		this.setChecks(EnhancedSecurityChecks.DISALLOW_POST_DATA, EnhancedSecurityChecks.ONLY_ALLOW_BASIC_METHODS);
	}

	private static final String SEGMENT = "api/v1/comments/";

	@SuppressWarnings("resource")
	@Override
	public Response onRequest(final Request request) {
		final UniJsonValue v = UniJsonValue.object();
		final String videoID;
		try {
			videoID = request.url().substring(request.url().indexOf(SEGMENT) + SEGMENT.length());
		} catch (IndexOutOfBoundsException ex) {
			v.add("error", true);
			v.add("error_message", "No videoID provided!");
			return new Response(404, v, v).setCustomMime("application/json");
		}
		try {
			final YTCommentInitData id = YTCommentInitData.make(videoID);
			final YouTubeCommentResult d = YTComments.getComments(id);
			v.add("commentCount", d.getComments().size());
			v.add("videoId", videoID);
			final UniJsonValue comments = UniJsonValue.array(d.getComments().size());
			for (final YTComment comment : d.getComments()) {
				final UniJsonValue o = UniJsonValue.object();
				o.add("author", comment.getAuthorName());
				final UniJsonValue authorThumbnails = UniJsonValue.array(1);
				final UniJsonValue authorThumbnail = UniJsonValue.object(4);
				authorThumbnail.add("url", comment.getAuthorThumbnail());
				authorThumbnail.add("width", 176);
				authorThumbnail.add("height", 176);
				authorThumbnails.add(authorThumbnail);
				o.add("authorThumbnails", authorThumbnails);
				o.add("authorId", "");
				o.add("authorUrl", "");
				o.add("isEdited", false);
				o.add("isPinned", comment.isPinned());
				o.add("content", comment.getComment());
				o.add("commentHtml", comment.getComment());
				o.add("published", -1L);
				o.add("publishedText", "N/A");
				o.add("likeCount", comment.getLikes());
				o.add("commentId", "");
				o.add("authorIsChannelOwner", false);
				comments.add(o);
			}
			v.add("comments", comments);
			if (d.hasCont())
				v.add("continuation", d.getCont());
			return new Response(200, v, v).setCustomMime("application/json");
		} catch (Exception ex) {
			JVM.errorln(ex);
			return new Response(503, v, v).setCustomMime("application/json");
		}
	}
}
